/**
 *
 * @author Tritonio
 */

package jrpc;

import java.awt.Canvas;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.image.AreaAveragingScaleFilter;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageProducer;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.zip.DeflaterInputStream;


class RemoteScreenReceiver implements Runnable {

    Thread runner;
    ObjectInputStream objectInputStream;
    RemoteScreenViewer myRSV;

    RemoteScreenReceiver(Connection connection, RemoteScreenViewer RSV) throws IOException {
        DeflaterInputStream deflatedInput = new DeflaterInputStream(connection.input);
        objectInputStream = new ObjectInputStream(deflatedInput);
        myRSV = RSV;
        runner = new Thread(this);
        runner.start();
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (runner==thisThread) {
            PositionedImageBuffer screenPart = null;
            try {
                screenPart = (PositionedImageBuffer) objectInputStream.readObject();
            } catch (IOException ex) {
                runner = null;
            } catch (ClassNotFoundException ex) {
                runner = null;
            }
            assert(!myRSV.closed);
            Graphics2D canvasBuffer = (Graphics2D) myRSV.canvas1.getGraphics();
            AreaAveragingScaleFilter scaler = new AreaAveragingScaleFilter(myRSV.canvas1.getWidth(), myRSV.canvas1.getHeight());
            ImageProducer imageProducer = new FilteredImageSource(screenPart.screenImage.getSource(),scaler);
            canvasBuffer.drawImage( (BufferedImage) Toolkit.getDefaultToolkit().createImage(imageProducer), null, screenPart.partX, screenPart.partY);
        }
    }

}
